package com.pactera.madp.cp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.em.user.StatusEnum;
import com.pactera.madp.cp.api.em.workcontact.AddWayEnum;
import com.pactera.madp.cp.api.em.workemployee.ContactInheritCodeEnum;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.vo.contact.ContactInheritVO;
import com.pactera.madp.cp.api.vo.employee.*;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.WorkContactEmployeeMapper;
import com.pactera.madp.cp.mapper.WorkEmployeeMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 在离职服务实现类
 *
 * @author yushen.qi
 * @since 2021-07-19 15:08:13
 */

@Slf4j
@Service("employeeInheritService")
public class EmployeeInheritServiceImpl extends ServiceImpl<WorkEmployeeMapper, WorkEmployeeEntity> implements EmployeeInheritService {

    @Resource
    private WorkContactEmployeeMapper workContactEmployeeMapper;
    @Resource
    private IWorkEmployeeService employeeService;
    @Resource
    private IWorkContactService iWorkContactService;
    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;
    @Autowired
    private IWorkRoomService roomService;
    @Autowired
    private TakeOverService takeOverService;

    @Override
    public IPage<EmployeeInheritVO> getListByChoose(Page page, String name, String mobile, Integer status) {
        Integer corpId = CorpContextHolder.getCorpId();
        return  baseMapper.getListByChoose(page,corpId, name, mobile, status);
    }

    @Override
    public IPage<ContactInheritVO> getContactByUser(Integer id, Page page) {
        //获取企业id
        Integer corpId = CorpContextHolder.getCorpId();
        //查询当前员工信息
        WorkEmployeeEntity workEmployeeEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getId, id).eq(WorkEmployeeEntity::getCorpId,corpId));
       //查询员工对应客户信息并分页
        contactList(workEmployeeEntity.getWxUserId());
        QueryWrapper<WorkContactEmployeeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id",id)
                .eq("corp_id",corpId)
                .eq("status",1);
        IPage<WorkContactEmployeeEntity> iPage = workContactEmployeeMapper.selectPage(page, wrapper);
        log.info("iPage"+iPage.getRecords());
        List<ContactInheritVO> collect = iPage.getRecords().stream().map(workContactEmployeeEntity -> {
            WorkContactEntity workContactEntity = iWorkContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                    .eq(WorkContactEntity::getId, workContactEmployeeEntity.getContactId())
                    .eq(WorkContactEntity::getCorpId,corpId));
            ContactInheritVO contactInheritVO = new ContactInheritVO();
            contactInheritVO.setAddWay(AddWayEnum.getByCode(workContactEmployeeEntity.getAddWay()));
            contactInheritVO.setEmployeeName(workEmployeeEntity.getName());
            contactInheritVO.setCreateTime(workContactEmployeeEntity.getCreateTime());
            contactInheritVO.setId(workContactEmployeeEntity.getContactId());
            contactInheritVO.setBusinessNo(workContactEntity.getBusinessNo());
            ArrayList<ContactInheritVO.tagVO> tagVOS = new ArrayList<>();
            //查询客户拥有的企业标签信息
            List<Map> contact = workContactEmployeeMapper.getContactById(corpId, workContactEmployeeEntity.getContactId());
            contact.forEach(map -> {
                Integer contactId = Integer.valueOf(String.valueOf(map.get("contact_id")));
                Integer contactTagId = Integer.valueOf(String.valueOf(map.get("contact_tag_id")));
                String tagName = String.valueOf(map.get("tag_name"));
                if(workContactEmployeeEntity.getContactId().equals(contactId)){
                    ContactInheritVO.tagVO tagVO = new ContactInheritVO.tagVO();
                    tagVO.setTagName(tagName);
                    tagVO.setContactTagId(contactTagId);
                    tagVOS.add(tagVO);
                }
            });
            List<ContactInheritVO.tagVO> vos = tagVOS.stream().distinct().collect(Collectors.toList());
            contactInheritVO.setStateInherit(ContactInheritCodeEnum.getTypeByCode(workContactEmployeeEntity.getStateInherit()));
            contactInheritVO.setContactName(workContactEntity.getName());
            contactInheritVO.setWxExternalUserid(workContactEntity.getWxExternalUserid());
            contactInheritVO.setTagList(vos);
            return contactInheritVO;
        }).collect(Collectors.toList());
        Page<ContactInheritVO> voPage = new Page<>();
        voPage.setRecords(collect);
        voPage.setSize(iPage.getSize());
        voPage.setCurrent(iPage.getCurrent());
        voPage.setTotal(iPage.getTotal());
        return voPage;
    }

    @Override
    public R updateContact(String oldWxUserId,String newWxUserId, String[] wxExternalUserid) {
       if(oldWxUserId.equals(newWxUserId)){
           throw new CheckedException("不能转接给自己！");
       }
        //获取企业微信id
        Integer corpId = CorpContextHolder.getCorpId();
        //获取跟进用户的信息
        WorkEmployeeEntity newEmployeeEntity = getEmployeeInfo(newWxUserId);
        //获取原跟进用户信息
        WorkEmployeeEntity oldEmployeeEntity = getEmployeeInfo(oldWxUserId);
       /* for (int i = 0; i < wxExternalUserid.length; i++) {
            String contactId = wxExternalUserid[i];
            WorkContactEmployeeEntity one = workContactEmployeeService.getOne(Wrappers
            .<WorkContactEmployeeEntity>lambdaQuery()
            .eq(WorkContactEmployeeEntity::getContactId, contactId)
            .eq(WorkContactEmployeeEntity::getEmployeeId, newEmployeeEntity.getId()));
            WorkContactEntity contactEntity = iWorkContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                    .eq(WorkContactEntity::getWxExternalUserid, contactId));
            if(null!=one){
                return R.failed("该用户已有当前转接客户："+contactEntity.getName());
            }
        }*/
        //调用企业微信api实现客户转接
        String result = WxApiUtils.contactInherit(corpId, oldWxUserId, newWxUserId, wxExternalUserid);
        JSONArray resultList = JSONArray.parseArray(result);
        ArrayList<InheritUpdateVO> inheritUpdateVOS = new ArrayList<>();
        for (int i = 0; i < resultList.toArray().length; i++) {
            JSONObject jsonObject = resultList.getJSONObject(i);
            String externalUserid = jsonObject.getString("external_userid");
            //获取客户信息
            WorkContactEntity contactEntity = getContactInfo(externalUserid);
            Integer value = Integer.valueOf(jsonObject.getString("errcode"));
            if(value==0){
                UpdateWrapper<WorkContactEmployeeEntity> wrapper = new UpdateWrapper<>();
                wrapper.set("new_employee_id",newEmployeeEntity.getId())
                        .eq("employee_id",oldEmployeeEntity.getId())
                        .eq("contact_id",contactEntity.getId());
                workContactEmployeeMapper.update(null, wrapper);
            }
            InheritUpdateVO inheritUpdateVO = new InheritUpdateVO();
            inheritUpdateVO.setName(contactEntity.getName());
            inheritUpdateVO.setMessage(ContactInheritCodeEnum.getTypeByCode(value));
            inheritUpdateVOS.add(inheritUpdateVO);
        }
        return R.ok(inheritUpdateVOS);
     }


    /**
     * 客户接替状态查询
     *
     * @param oldWxUserId 原跟进成员的userid
     * @return
     */
    public void contactList(String oldWxUserId) {
        Integer corpId = CorpContextHolder.getCorpId();
        //获取原跟进用户信息
        WorkEmployeeEntity oldEmployeeEntity = getEmployeeInfo(oldWxUserId);
        //获取用户和客户的关联信息
        //获取跟进用户的信息，存在多个跟进用户
        List<WorkContactEmployeeEntity> list = workContactEmployeeService.list(Wrappers
                .<WorkContactEmployeeEntity>lambdaQuery()
                .eq(WorkContactEmployeeEntity::getCorpId, corpId)
                .eq(WorkContactEmployeeEntity::getEmployeeId, oldEmployeeEntity.getId()));
        for (int i = 0; i < list.size(); i++) {
            WorkContactEmployeeEntity entity = list.get(i);
            if(entity.getNewEmployeeId()==null){
               continue;
            }
            //获取新用户的信息
            WorkEmployeeEntity newEmployeeEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getCorpId,corpId)
                    .eq(WorkEmployeeEntity::getId,entity.getNewEmployeeId()));
            //调用企业微信api查询客户的转接状态
            String res = WxApiUtils.contactInheritStatus(corpId, oldWxUserId,newEmployeeEntity.getWxUserId());
            JSONArray array = JSONArray.parseArray(res);
            if(null==array){
                    WorkContactEmployeeEntity updateEntity = new WorkContactEmployeeEntity();
                    updateEntity.setStateInherit(3);
                    workContactEmployeeService.update(updateEntity, Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                            .eq(WorkContactEmployeeEntity::getCorpId,corpId)
                            .eq(WorkContactEmployeeEntity::getNewEmployeeId, newEmployeeEntity.getId())
                            .eq(WorkContactEmployeeEntity::getContactId, entity.getContactId())
                            .eq(WorkContactEmployeeEntity::getEmployeeId, oldEmployeeEntity.getId()));
                    continue;
            }
            //获取新用户的信息
            for (int j = 0; j <= array.toArray().length-1; j++) {
                //通过传回来的字段拼接返回前端展示的字段
                JSONObject jsonObject = array.getJSONObject(j);
                String externalUserid = jsonObject.getString("external_userid");
//            获取客户的信息
                WorkContactEntity contactEntity = getContactInfo(externalUserid);
                Integer status = Integer.valueOf(jsonObject.getString("status"));
                //根据转接情况更新用户-客户关联表
                if(status==1){
                    //删除原对应关系
                    workContactEmployeeService.remove(Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                            .eq(WorkContactEmployeeEntity::getCorpId,corpId)
                            .eq(WorkContactEmployeeEntity::getEmployeeId,oldEmployeeEntity.getId())
                            .eq(WorkContactEmployeeEntity::getContactId,contactEntity.getId())
                            .eq(WorkContactEmployeeEntity::getNewEmployeeId,newEmployeeEntity.getId()));
                    //takeOverService.add(corpId);
                }
                WorkContactEmployeeEntity updateEntity = new WorkContactEmployeeEntity();
                updateEntity.setStateInherit(status);
                workContactEmployeeService.update(updateEntity, Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                        .eq(WorkContactEmployeeEntity::getCorpId,corpId)
                        .eq(WorkContactEmployeeEntity::getNewEmployeeId, newEmployeeEntity.getId())
                        .eq(WorkContactEmployeeEntity::getContactId, contactEntity.getId())
                        .eq(WorkContactEmployeeEntity::getEmployeeId, oldEmployeeEntity.getId()));
            }
        }
    }

    @Override
    public R resignedUserToContact(Page page,String cursor) {
//        分页数据
           String pageId=String.valueOf(page.getCurrent());
           String pageSize=String.valueOf(page.getSize());
        Integer corpId = CorpContextHolder.getCorpId();
//        获取待分配的离职成员的客户列表
        String contactByResignedList = WxApiUtils.contactByResignedList(corpId,pageId,pageSize, cursor);
        JSONArray array = JSONArray.parseArray(contactByResignedList);
        if(array==null){
            throw new CheckedException("该用户暂无客户");
        }
        ArrayList<EmployeeResignedInheritVO> vos = new ArrayList<>();
//        排序字段
        AtomicReference<Integer> j= new AtomicReference<>(1);
        for (int i = 0; i < array.toArray().length; i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            String handoverUserid = jsonObject.getString("handover_userid");
            String externalUserid = jsonObject.getString("external_userid");
            String resignedTime = jsonObject.getString("dimission_time");
//            获取离职员工的信息
            WorkEmployeeEntity employeeEntity = getEmployeeInfo(handoverUserid);
//            获取客户的信息
            WorkContactEntity contactEntity = getContactInfo(externalUserid);
            String time = stringChangeDate(resignedTime);
            EmployeeResignedInheritVO vo = new EmployeeResignedInheritVO();
            Integer andSet = j.getAndSet(j.get() + 1);
            vo.setId(andSet);
            vo.setHandoverName(employeeEntity.getName());
            vo.setExternalName(contactEntity.getName());
            vo.setResignedTime(time);
            vo.setHandoverUserid(handoverUserid);
            vo.setExternalUserid(externalUserid);
            vos.add(vo);
        }
     return R.ok(PageUtil.split(vos,Integer.valueOf(pageId),Integer.valueOf(pageSize)));
    }


    @Override
    public R resignedContactByUser(String oldWxUserId, String newWxUserId, String[] wxExternalUserid) {
        //获取企业微信id
        Integer corpId = CorpContextHolder.getCorpId();
        //获取跟进用户的信息
        WorkEmployeeEntity newEmployeeEntity = getEmployeeInfo(newWxUserId);
        //获取原跟进用户信息
        WorkEmployeeEntity oldEmployeeEntity = getEmployeeInfo(oldWxUserId);
        //调用企业微信api实现客户转接
        String result = WxApiUtils.contactByResigned(corpId, oldWxUserId, newWxUserId, wxExternalUserid);
        JSONArray resultList = JSONArray.parseArray(result);
        ArrayList<InheritUpdateVO> inheritUpdateVOS = new ArrayList<>();
        for (int i = 0; i < resultList.toArray().length; i++) {
            JSONObject jsonObject = resultList.getJSONObject(i);
            String externalUserid = jsonObject.getString("external_userid");
            //获取客户信息
            WorkContactEntity contactEntity = getContactInfo(externalUserid);
            Integer value = Integer.valueOf(jsonObject.getString("errcode"));
            InheritUpdateVO inheritUpdateVO = new InheritUpdateVO();
            inheritUpdateVO.setName(contactEntity.getName());
            inheritUpdateVO.setMessage(ContactInheritCodeEnum.getTypeByCode(value));
            inheritUpdateVOS.add(inheritUpdateVO);
        }
        //查询客户转接情况
        String res = WxApiUtils.contactInheritStatus(corpId, oldWxUserId, newWxUserId);
        JSONArray array = JSONArray.parseArray(res);
        //可能存在多个用户转接情况，遍历
        for (int i = 0; i <= array.toArray().length-1; i++) {
            //获取客户转接情况
            JSONObject jsonObject = array.getJSONObject(i);
            String externalUserid = jsonObject.getString("external_userid");
            Integer status = Integer.valueOf(jsonObject.getString("status"));
            //获取客户信息
            WorkContactEntity contactEntity = getContactInfo(externalUserid);
            //根据转接情况更新用户-客户关联表，继承状态说明：1-接替完毕 2-等待接替 3-客户拒绝 4-接替成员客户达到上限 5-无接替记录
            if(status==1){
                //删除原对应关系
                workContactEmployeeService.remove(Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                        .eq(WorkContactEmployeeEntity::getCorpId,corpId)
                        .eq(WorkContactEmployeeEntity::getEmployeeId,oldEmployeeEntity.getId())
                        .eq(WorkContactEmployeeEntity::getContactId,contactEntity.getId()));
            }
                WorkContactEmployeeEntity updateEntity = new WorkContactEmployeeEntity();
                updateEntity.setStateInherit(status);
                workContactEmployeeService.update(updateEntity,Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                        .eq(WorkContactEmployeeEntity::getCorpId,corpId)
                        .eq(WorkContactEmployeeEntity::getEmployeeId,newEmployeeEntity.getId())
                        .eq(WorkContactEmployeeEntity::getContactId,contactEntity.getId()));

        }
        return R.ok(inheritUpdateVOS);
    }

    @Override
    public R resignedGroupToUser(String[] groupId, String newWxUserId) {
        Integer corpId = CorpContextHolder.getCorpId();
//        调用企业微信api实现客户群继承
        String result = WxApiUtils.contactByResignedGroup(corpId, groupId, newWxUserId);
        JSONArray resultList = JSONArray.parseArray(result);
        ArrayList<ResignedGroupInheritVO> groupInheritVOS = new ArrayList<>();
        if(null==resultList){
            return R.ok(null,"转接成功");
        }
        for (int i = 0; i < resultList.toArray().length; i++) {
            JSONObject jsonObject = resultList.getJSONObject(i);
            String wxChatId = jsonObject.getString("chat_id");
            //获取客户群信息
            WorkRoomEntity roomEntity = roomService.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                    .eq(WorkRoomEntity::getCorpId,corpId)
                    .eq(WorkRoomEntity::getWxChatId, wxChatId));
            Integer value = Integer.valueOf(jsonObject.getString("errcode"));
            ResignedGroupInheritVO groupInheritVO = new ResignedGroupInheritVO();
            groupInheritVO.setWxChatGroupName(roomEntity.getName());
            groupInheritVO.setMessage(ContactInheritCodeEnum.getTypeByCode(value));
            groupInheritVO.setWxChatId(wxChatId);
            groupInheritVOS.add(groupInheritVO);
        }
        return R.ok(groupInheritVOS);
    }

    @Override
    public R<Page<EmployeeResignedGroupInheritVO>> groupStatus(Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
//        获取群主已离职的客户群
        List<WorkEmployeeEntity> employeeEntities = employeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getStatus, 5)
                .eq(BaseEntity::getDelFlag, 0)
                .eq(WorkEmployeeEntity::getCorpId, corpId));
        ArrayList<EmployeeResignedGroupInheritVO> groupInheritVOS = new ArrayList<>();
        employeeEntities.forEach(workEmployeeEntity -> {
            List<WorkRoomEntity> roomEntities = roomService.list(Wrappers.<WorkRoomEntity>lambdaQuery().eq(WorkRoomEntity::getOwnerId, workEmployeeEntity.getId()));
            roomEntities.forEach(workRoomEntity -> {
                EmployeeResignedGroupInheritVO groupInheritVO = new EmployeeResignedGroupInheritVO();
                groupInheritVO.setId(workRoomEntity.getId());
                groupInheritVO.setWxChatId(workRoomEntity.getWxChatId());
                groupInheritVO.setStatus(StatusEnum.getTypeByCode(workRoomEntity.getStatus()));
                groupInheritVOS.add(groupInheritVO);
            });
        });
        return R.ok(PageUtil.split(groupInheritVOS, Integer.valueOf(String.valueOf(page.getCurrent())), Integer.valueOf(String.valueOf(page.getSize()))));
    }

    /**
     * 往字符串数组追加新数据
     *
     * @param arr  数组
     * @param str  新数值
     * @return
     */
    private static String[] insert(String[] arr, String str) {
        //获取数组长度
        int size = arr.length;
        //新建临时字符串数组，在原来基础上长度加一
        String[] tmp = new String[size + 1];
        //先遍历将原来的字符串数组数据添加到临时字符串数组
        System.arraycopy(arr, 0, tmp, 0, size);
        //在最后添加上需要追加的数据
        tmp[size] = str;
        //返回拼接完成的字符串数组
        return tmp;
    }

    /**
     * 时间戳转换
     *
     * @param time
     * @return
     */
    private static String stringChangeDate(String time){
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long lt = new Long(time);
    Date date = new Date(lt);
    String format = simpleDateFormat.format(date);
    return format;
    }


    /**
     * 获取用户信息
     *
     * @param wxUserId 用户唯一id
     * @return WorkEmployeeEntity
     */
    public WorkEmployeeEntity getEmployeeInfo(String wxUserId){
        Integer corpId = CorpContextHolder.getCorpId();
        return employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getCorpId,corpId)
                .eq(WorkEmployeeEntity::getWxUserId, wxUserId));
    }

    /**
     * 获取客户信息
     *
     * @param wxExternalUserid 客户唯一id
     * @return WorkContactEntity
     */
    public WorkContactEntity getContactInfo(String wxExternalUserid){
        Integer corpId = CorpContextHolder.getCorpId();
        return iWorkContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getCorpId,corpId)
                .eq(WorkContactEntity::getWxExternalUserid, wxExternalUserid));
    }
}
